package com.ytjj.quartz.service;

import com.ytjj.common.exception.ApiException;
import com.ytjj.qmyx.mall.model.PageSourceStatistics;
import com.ytjj.quartz.dao.AnalysisStatisticsDao;
import com.ytjj.quartz.dao.OrdersDao;
import com.ytjj.quartz.dao.OrdersInfoDao;
import com.ytjj.quartz.dao.PageSourceDao;
import com.ytjj.quartz.enums.PageSourceEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;

/**
 *
 *
 * @Version: 1.0
 */
@Service
@Slf4j
public class PageSourceService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private AnalysisStatisticsDao analysisStatisticsDao;

    @Autowired
    private OrdersInfoDao ordersInfoDao;

    @Autowired
    private PageSourceDao pageSourceDao;


    @Transactional(rollbackFor = Exception.class)
    public void updatePageSource(String startTime, String endTime, String operation) {

        PageSourceEnums[] pageSourceEnumsArr = PageSourceEnums.values();
        for(PageSourceEnums pageSourceEnums : pageSourceEnumsArr){
            String pageSource = pageSourceEnums.name();
            String pathCode = pageSourceEnums.getPathCode();
            // uv
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            int preDay = cal.get(Calendar.DATE) - 1;
            int day = cal.get(Calendar.DATE);
            int nextDay = cal.get(Calendar.DATE) + 1;
            String selectTime = null;
            if (operation.equals("fiveFlush")) {
                selectTime = year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
            } else {
                selectTime = year + "-" + (month < 10 ? "0" + month : month) + "-" + (preDay < 10 ? "0" + preDay : preDay);
            }
            Integer uv = Optional.ofNullable(analysisStatisticsDao.getUvByPageCode(pathCode, selectTime))
                    .orElseGet(() -> 0);
            // 订单数
            Integer orderNum = Optional.ofNullable(ordersInfoDao.getOrderNum(pageSource, startTime, endTime))
                    .orElseGet(() -> 0);
            // 实际订单数
            Integer realOrderNum = Optional.ofNullable(ordersInfoDao.getRealOrderNum(pageSource, startTime, endTime))
                    .orElseGet(() -> 0);
            // 支付订单数
            Integer payNum = Optional.ofNullable(ordersInfoDao.getPayNum(pageSource, startTime, endTime))
                    .orElseGet(() -> 0);
            // 支付率
            BigDecimal payRatioNo = BigDecimal.ZERO;
            if(orderNum != 0) {
                payRatioNo = BigDecimal.valueOf(payNum).divide(BigDecimal.valueOf(orderNum), 4, BigDecimal.ROUND_DOWN);
            }
            String payRatio = payRatioNo + "";
            // 支付金额
            BigDecimal payMoney = ordersInfoDao.getPayMoney(pageSource, startTime, endTime);
            if(payMoney == null) {
                payMoney = BigDecimal.ZERO;
            }
            // 成本
            BigDecimal costMoney = ordersInfoDao.getCostAmount(pageSource, startTime, endTime);
            if(costMoney == null) {
                costMoney = BigDecimal.ZERO;
            }
            // 利润
            BigDecimal profit = BigDecimal.ZERO;
            if(payMoney != null && costMoney != null) {
                profit = payMoney.subtract(costMoney).setScale(2, BigDecimal.ROUND_DOWN);
            }
            //订单率
            BigDecimal orderRatioNo = BigDecimal.ZERO;
            if(uv != 0) {
                orderRatioNo = BigDecimal.valueOf(realOrderNum.longValue()).divide(BigDecimal.valueOf(uv.longValue()), 4, BigDecimal.ROUND_DOWN);
            }
            String orderRatio = orderRatioNo + "";
            //客单率
            BigDecimal customerRatioNo = BigDecimal.ZERO;
            if(payNum != 0) {
                customerRatioNo = payMoney.divide(BigDecimal.valueOf(payNum.longValue()), 2, BigDecimal.ROUND_DOWN);
            }
            String customerRatio = customerRatioNo + "";

            PageSourceStatistics pageSourceStatistics = new PageSourceStatistics();
            pageSourceStatistics.setPageSource(pageSource);
            pageSourceStatistics.setUv(uv);
            pageSourceStatistics.setOrderNum(orderNum);
            pageSourceStatistics.setRealOrderNum(realOrderNum);
            pageSourceStatistics.setPayNum(payNum);
            pageSourceStatistics.setPayRatio(payRatio);
            pageSourceStatistics.setPayMoney(payMoney);
            pageSourceStatistics.setCostMoney(costMoney);
            pageSourceStatistics.setProfit(profit);
            pageSourceStatistics.setOrderRatio(orderRatio);
            pageSourceStatistics.setCustomerRatio(customerRatio);
            pageSourceStatistics.setCreateTime(new Date());
            pageSourceStatistics.setRecordTime(new Date());

            if(operation.equals("fiveFlush")) {
                PageSourceStatistics pst = pageSourceDao.getPageStatistics(pageSource);

                if(pst != null) {
                    pageSourceStatistics.setId(pst.getId());
                    pageSourceStatistics.setRecordTime(new Date());
                    pageSourceDao.updatePageSource(pageSourceStatistics);
                } else {
                    pageSourceDao.insertPageSource(pageSourceStatistics);
                }

            } else if (operation.equals("onlyTwoFlush")) {
                pageSourceStatistics.setRecordTime(new Date());
                pageSourceDao.flushPageSource(pageSourceStatistics);
            } else {
                throw new ApiException("订单来源统计定时器出现异常，请检查！");
            }

        }

    }

}
